package com.ptkc.web;

import com.ptkc.constants.Page;
import com.ptkc.constants.WebResult;
import com.ptkc.data.repository.DeliverCostRepository;
import com.ptkc.utils.DatesUtil;
import com.ptkc.utils.MyUtil;
import com.ptkc.utils.NumberUtils;
import com.ptkc.utils.StringUtil;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.builders.PointBuilder;
import org.elasticsearch.common.geo.builders.ShapeBuilders;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.ScriptScoreFunctionBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月27日
 */
@RestController
@RequestMapping(value = {"/business", "search/business"})
public class BusController {

    private final String INDEX = "runfast_business";

    private final String TYPE = "business";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private DeliverCostRepository deliverCostRepository;

    private final String[] exclude = {"activities", "busPoint", "distRangeShape" , "delivercost", "selfDistRangeShape"};

    @GetMapping(value = "/list")
    public WebResult<Page<?>> getBusList(@PageableDefault Pageable pageable, HttpServletRequest request) throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        String agents = request.getParameter("agents");
        if(agents != null && StringUtil.isNotEmpty(agents)){
            queryBuilder.must(QueryBuilders.termsQuery("agentId", agents.split(",")));
        }
        String name = request.getParameter("name");
        if(StringUtil.isNotEmpty(name)){
            queryBuilder.must(QueryBuilders.prefixQuery("name", name));
        }
        String statusx = request.getParameter("statusx");
        if("1".equals(statusx)){
            queryBuilder.must(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("statusx", -1)));
        }else if("-1".equals(statusx)){
            queryBuilder.must(QueryBuilders.termQuery("statusx", -1));
        }
        String mainClassId = request.getParameter("mainClassId");
        if(StringUtil.isNotEmpty(mainClassId)){
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.should(QueryBuilders.termQuery("mainClassId", mainClassId));
            boolQueryBuilder.should(QueryBuilders.termQuery("subClassId1", mainClassId));
            boolQueryBuilder.should(QueryBuilders.termQuery("subClassId2", mainClassId));
            queryBuilder.must(boolQueryBuilder);
        }
        String qualityLevel = request.getParameter("qualityLevel");
        if(StringUtil.isNotEmpty(qualityLevel)){
            if(qualityLevel.equalsIgnoreCase("1")){
                queryBuilder.must(QueryBuilders.rangeQuery("thisMonthOrderQuantity").gte(500));
            }else if(qualityLevel.equalsIgnoreCase("2")){
                queryBuilder.must(QueryBuilders.rangeQuery("thisMonthOrderQuantity").from(300, true).to(500, true));
            }else if(qualityLevel.equalsIgnoreCase("3")){
                queryBuilder.must(QueryBuilders.rangeQuery("thisMonthOrderQuantity").from(100, true).to(300, true));
            }else if(qualityLevel.equalsIgnoreCase("4")){
                queryBuilder.must(QueryBuilders.rangeQuery("thisMonthOrderQuantity").from(30, true).to(100, true));
            }else if(qualityLevel.equalsIgnoreCase("5")){
                queryBuilder.must(QueryBuilders.rangeQuery("thisMonthOrderQuantity").from(1, true).to(30, true));
            }else if(qualityLevel.equalsIgnoreCase("6")) {
                BoolQueryBuilder queryBuilders = QueryBuilders.boolQuery();
                queryBuilders.should(QueryBuilders.termQuery("thisMonthOrderQuantity", 0));
                BoolQueryBuilder notQueryBuilder = QueryBuilders.boolQuery();
                notQueryBuilder.mustNot(QueryBuilders.existsQuery("thisMonthOrderQuantity"));
                queryBuilders.should(notQueryBuilder);
                queryBuilder.must(queryBuilders);
            }
        }
        String statu = request.getParameter("statu");
        if(StringUtil.isNotEmpty(statu)){
            queryBuilder.must(QueryBuilders.termQuery("statu", statu));
        }
        String isDeliver = request.getParameter("isDeliver");
        if(StringUtil.isNotEmpty(isDeliver)){
            queryBuilder.must(QueryBuilders.termQuery("isDeliver", isDeliver));
        }
        String suportSelf = request.getParameter("suportSelf");
        if(StringUtil.isNotEmpty(suportSelf)){
            queryBuilder.must(QueryBuilders.termQuery("suportSelf", suportSelf));
        }
        String authenticationStatus = request.getParameter("authenticationStatus");
        if(StringUtil.isNotEmpty(authenticationStatus)){
            if(authenticationStatus.equalsIgnoreCase("1")){
                queryBuilder.must(QueryBuilders.termQuery("mainCert", 1));
                queryBuilder.must(QueryBuilders.termQuery("tradeCert", 1));
            }else if(authenticationStatus.equalsIgnoreCase("2")){
                BoolQueryBuilder one = QueryBuilders.boolQuery();
                one.should(QueryBuilders.termQuery("mainCert", 0));
                BoolQueryBuilder notQueryBuilder = QueryBuilders.boolQuery();
                one.should(notQueryBuilder.mustNot(QueryBuilders.existsQuery("mainCert")));
                queryBuilder.must(one);
                BoolQueryBuilder tow = QueryBuilders.boolQuery();
                tow.should(QueryBuilders.termQuery("tradeCert", 0));
                BoolQueryBuilder notQueryBuilder1 = QueryBuilders.boolQuery();
                tow.should(notQueryBuilder1.mustNot(QueryBuilders.existsQuery("tradeCert")));
                queryBuilder.must(tow);
            }else if(authenticationStatus.equalsIgnoreCase("3")){

                BoolQueryBuilder t1 = QueryBuilders.boolQuery();
                t1.must(QueryBuilders.termQuery("mainCert", 1));
                BoolQueryBuilder certNot = QueryBuilders.boolQuery();
                certNot.should(QueryBuilders.termQuery("tradeCert", 0));
                certNot.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("tradeCert")));
                t1.must(certNot);

                BoolQueryBuilder t2 = QueryBuilders.boolQuery();
                t2.must(QueryBuilders.termQuery("tradeCert", 1));
                BoolQueryBuilder mainNot = QueryBuilders.boolQuery();
                mainNot.should(QueryBuilders.termQuery("mainCert", 0));
                mainNot.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("mainCert")));
                t2.must(mainNot);

                queryBuilder.must(QueryBuilders.boolQuery().should(t1).should(t2));
            }
        }
        String mobile = request.getParameter("mobile");
        if(StringUtil.isNotEmpty(mobile)){
            queryBuilder.must(QueryBuilders.termQuery("mobile", mobile));
        }
        sourceBuilder.query(queryBuilder).from((int)pageable.getOffset()).size(pageable.getPageSize()).sort("createTime", SortOrder.DESC);
        sourceBuilder.fetchSource(null, exclude);
        searchRequest.source(sourceBuilder).indices(INDEX).types(TYPE);
        SearchResponse response = restHighLevelClient.search(searchRequest);
        if(response.status() == null){
            return WebResult.fail("查询失败");
        }else if(response.status() != RestStatus.OK){
            return WebResult.fail("搜索服务请求失败.");
        }else {
            List<Object> rows = new ArrayList<>();
            SearchHits searchHits = response.getHits();
            for(SearchHit hit : searchHits.getHits()){
                rows.add(hit.getSourceAsMap());
            }
            return WebResult.ok(new Page<>(searchHits.getTotalHits(), pageable.getPageNumber(), pageable.getPageSize(), rows));
        }
    }


    @GetMapping(value = "/quantitative")
    public WebResult<Object> statistical(HttpServletRequest request) throws IOException {
        String agents = request.getParameter("agents");
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder parentQueryBuilder = QueryBuilders.boolQuery();

        Collection<Integer> agents_array = new ArrayList<>();
        if(agents != null && StringUtil.isNotEmpty(agents)){
            String[] agentsStrArrays = agents.split(",");
            for(String agentId : agentsStrArrays){
                if(NumberUtils.isPositiveInteger(agentId)){
                    agents_array.add(Integer.valueOf(agentId));
                }
            }
        }

        if(agents_array.size() > 0){
            parentQueryBuilder.must(QueryBuilders.termsQuery("agentId" , agents_array));
        }

        BoolQueryBuilder statusxQuery = QueryBuilders.boolQuery();
        statusxQuery.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("statusx")));
        statusxQuery.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("statusx", -1)));
        parentQueryBuilder.must(statusxQuery);

        Map<String,Object> paramsThreeDayNoOrder = new HashMap<>();
        paramsThreeDayNoOrder.put("time", MyUtil.getBeforeDay(DatesUtil.getDayEnd(), -3).getTime());
        SumAggregationBuilder threeDayNoOrder = AggregationBuilders.sum("threeDayNoOrder").script(new Script(ScriptType.STORED,null, "runfast_business_last_order_compare", paramsThreeDayNoOrder));


        Date currTime1790 = MyUtil.set(System.currentTimeMillis(), 1970, 0, 1);
        String today = String.valueOf(MyUtil.getDayOfWeek(new Date()));
        Map<String, Map<String,Double>> deliverCostMap = deliverCostRepository.getDeliverCost(agents_array);
        Map<String, Object> openingMap = new HashMap<>();
        openingMap.put("deliverCostMap", deliverCostMap);
        openingMap.put("time", currTime1790.getTime());
        openingMap.put("today", today);
        Script openingScript = new Script(ScriptType.STORED, null, "runfast_new_bus_opened_sort", openingMap);
        SumAggregationBuilder openingBus = AggregationBuilders.sum("openingBus").script(openingScript);
//
//        Date date = new Date();
//        Map<String, Object> paramsOpening = new HashMap<>();
//        paramsOpening.put("today", String.valueOf(MyUtil.getDayOfWeek(date)));
//        paramsOpening.put("time", MyUtil.set(date.getTime(), 1970, 0, 1).getTime());
//        SumAggregationBuilder openingBus = AggregationBuilders.sum("openingBus").script(new Script(ScriptType.STORED, null, "runfast_business_is_workday", paramsOpening));

        ValueCountAggregationBuilder countTotal = AggregationBuilders.count("totalBus").field("id");

        sourceBuilder.query(parentQueryBuilder).aggregation(threeDayNoOrder).aggregation(openingBus).aggregation(countTotal).from(0).size(0);
        sourceBuilder.fetchSource(null, exclude);
        searchRequest.source(sourceBuilder).indices(INDEX).types(TYPE);
        System.out.println(searchRequest.source());
        SearchResponse response = restHighLevelClient.search(searchRequest);
        if(response.status() == null){
            return WebResult.fail("查询失败");
        }else if(response.status() != RestStatus.OK){
            return WebResult.fail("搜索服务请求失败.");
        }else {
            Map<String, Object> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            if(aggregations != null) {
                Sum noorders3 = aggregations.get("threeDayNoOrder");
                Sum opening = aggregations.get("openingBus");
                ValueCount totalBus = aggregations.get("totalBus");
                result.put("validBusinessCount", (int) opening.getValue());
                result.put("noOrdersInThreeBusinessCount", (int) noorders3.getValue());
                result.put("businessCount", totalBus.getValue());
                result.put("total", response.getHits().getTotalHits());
            }else{
                result.put("validBusinessCount", 0);
                result.put("noOrdersInThreeBusinessCount", 0);
                result.put("businessCount", 0);
                result.put("total", 0);
            }
            return WebResult.ok(result);
        }
    }


//    @GetMapping(value = "/area_search")
//    public WebResult<Page<Object>> getBusAreaDictance(String sort, String isDeliver, String supporSelf, String goldBus, String newBus, String zeorStartDelivery, @PageableDefault Pageable pageable, HttpServletRequest request) throws IOException {
//        String isOpening = request.getParameter("isopen");
//        String latStr = request.getParameter("lat");
//        String lngStr = request.getParameter("lon");
//        if(!NumberUtils.isRealNumber(latStr) || !NumberUtils.isRealNumber(lngStr)){
//            return WebResult.fail("位置坐标错误!");
//        }
//
//        String mainClassId = request.getParameter("mainClassId");
//
//        double lat = Double.valueOf(latStr);
//        double lon = Double.valueOf(lngStr);
//        Date now = new Date();
//        Date dateOf1970 = MyUtil.set(now.getTime(), 1970, 0, 1);
//        long timeOf1970 = dateOf1970.getTime();
//        SearchRequest searchRequest = new SearchRequest();
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        BoolQueryBuilder parentQueryBuilder = QueryBuilders.boolQuery();
//        PointBuilder builder = ShapeBuilders.newPoint(lon,lat);
//
//        //配送范围
//        BoolQueryBuilder selfDeliverBuilder = QueryBuilders.boolQuery();
//        selfDeliverBuilder.mustNot(QueryBuilders.termQuery("isDeliver", 1));
//        selfDeliverBuilder.must(QueryBuilders.geoShapeQuery("distRangeShape", builder));
//        BoolQueryBuilder merchantDeliverBuilder = QueryBuilders.boolQuery();
//        merchantDeliverBuilder.must(QueryBuilders.termQuery("isDeliver", 1));
//        merchantDeliverBuilder.must(QueryBuilders.geoShapeQuery("selfDistRangeShape", builder));
//        parentQueryBuilder.must(QueryBuilders.boolQuery().should(selfDeliverBuilder).should(merchantDeliverBuilder));
//
//        parentQueryBuilder.mustNot(QueryBuilders.termQuery("statusx", -1));
//
//        if(NumberUtils.isPositiveInteger(mainClassId)){
//            parentQueryBuilder.must(QueryBuilders.termQuery(mainClassId, Integer.valueOf(mainClassId)));
//        }
//
//        Date date = new Date();
//
//        //正在营业的商家
//        if("true".equalsIgnoreCase(isOpening)) {
//            Map<String, Object> isOpenParamMap = new HashMap<>();
//            isOpenParamMap.put("today", String.valueOf(MyUtil.getDayOfWeek(date)));
//            isOpenParamMap.put("time", MyUtil.set(date.getTime(), 1970, 0, 1).getTime());
//            isOpenParamMap.put("timeOf1790", timeOf1970);
//            Script script = new Script(ScriptType.STORED, null, "runfast_bus_query_criteria_isopened", isOpenParamMap);
//            parentQueryBuilder.must(QueryBuilders.scriptQuery(script));
//        }
//        //自配送
//        if("true".equalsIgnoreCase(isDeliver)){
//            parentQueryBuilder.must(QueryBuilders.termQuery("isDeliver", 1));
//        }else if("false".equalsIgnoreCase(isDeliver)){
//            //平台配送
//            BoolQueryBuilder plamDeliverBuilder = QueryBuilders.boolQuery();
//            plamDeliverBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("isDeliver", 1)));
//            plamDeliverBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("isDeliver")));
//            parentQueryBuilder.must(plamDeliverBuilder);
//        }
//        //支持自取
//        if("true".equalsIgnoreCase(supporSelf)){
//            parentQueryBuilder.must(QueryBuilders.termQuery("suportSelf", true));
//        }else if("false".equalsIgnoreCase(supporSelf)){
//            //不支持自取
//            parentQueryBuilder.mustNot(QueryBuilders.termQuery("suportSelf", true));
//        }
//        //金牌商家
//        if("true".equalsIgnoreCase(goldBus)){
//            parentQueryBuilder.must(QueryBuilders.termQuery("goldBusiness", true));
//        }else if("false".equalsIgnoreCase(goldBus)){
//            //非金牌商家
//            parentQueryBuilder.mustNot(QueryBuilders.termQuery("goldBusiness", true));
//        }
//        //新的商家
//        if("true".equalsIgnoreCase(newBus)){
//            parentQueryBuilder.must(QueryBuilders.rangeQuery("createTime").from(MyUtil.addTimeSpan(now, 0, -10).getTime(),true).to(now.getTime(),true));
//        }
//        //0元起送
//        if("true".equalsIgnoreCase(zeorStartDelivery)){
//            parentQueryBuilder.must(QueryBuilders.termQuery("startPay", 0));
//        }
//        //满减优惠
//        String fullReduction = request.getParameter("fullReduction");
//        //折扣商品
//        String discountMerchandise = request.getParameter("discountMerchandise");
//        //免配送费
//        String freeDistribution = request.getParameter("freeDistribution");
//        //首单立减
//        String firstReduction = request.getParameter("firstReduction");
//        //进店领券
//        String admissionTicket = request.getParameter("admissionTicket");
//        //优惠商家
//        String discountMerchant = request.getParameter("discountMerchant");
//        if("true".equalsIgnoreCase(fullReduction) || "true".equalsIgnoreCase(discountMerchandise) ||
//                "true".equalsIgnoreCase(freeDistribution) || "true".equalsIgnoreCase(firstReduction) ||
//                "true".equalsIgnoreCase(admissionTicket) || "true".equalsIgnoreCase(discountMerchant)){
//            BoolQueryBuilder nestedQuery = QueryBuilders.boolQuery();
//            Date curr_time = new Date();
//            nestedQuery.must(QueryBuilders.rangeQuery("activities.startTime").lte(curr_time.getTime())).must(QueryBuilders.rangeQuery("activities.endTime").gte(curr_time.getTime()));
//
//            if(!"true".equalsIgnoreCase(discountMerchant)){
//                if(fullReduction != null){
//                    nestedQuery.must(QueryBuilders.termQuery("activities.type", 1));
//                }
//                if(discountMerchandise != null){
//                    nestedQuery.must(QueryBuilders.termsQuery("activities.type", new int[]{2,4}));
//                }
//                if(freeDistribution != null){
//                    nestedQuery.must(QueryBuilders.termsQuery("activities.type", new int[]{5,7}));
//                }
//                if(firstReduction != null){
//                    nestedQuery.must(QueryBuilders.termQuery("activities.type", 9));
//                }
//                if(admissionTicket != null){
//                    nestedQuery.must(QueryBuilders.termQuery("activities.type", 10));
//                }
//            }
//            NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("activities", nestedQuery, ScoreMode.None);
//            parentQueryBuilder.must(nestedQueryBuilder);
//        }
//        sourceBuilder.query(parentQueryBuilder);
//        //距离
//        Map<String, Object> distanceParamMap = new HashMap<>();
//        distanceParamMap.put("lat", lat);
//        distanceParamMap.put("lon", lon);
//        Script distanceScript = new Script(ScriptType.STORED, null, "runfast_bus_point_distance", distanceParamMap);
//
//        Map<String, Object> paramsOpening = new HashMap<>();
//        paramsOpening.put("today", String.valueOf(MyUtil.getDayOfWeek(date)));
//        paramsOpening.put("time", MyUtil.set(date.getTime(), 1970, 0, 1).getTime());
//        paramsOpening.put("timeOf1790", timeOf1970);
//        Script isOpenScript = new Script(ScriptType.STORED, null, "runfast_bus_isopened", paramsOpening);
//
//        sourceBuilder.fetchSource(null, exclude).scriptField("isOpened", isOpenScript).scriptField("distance", distanceScript);
//
//        sourceBuilder.sort(SortBuilders.scriptSort(isOpenScript, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.DESC));
//        Script scriptBookable = new Script(ScriptType.STORED, null, "runfast_bus_sort_bookable", paramsOpening);
//        sourceBuilder.sort(SortBuilders.scriptSort(scriptBookable, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.DESC));
//
//        //排序
//        if("sales".equalsIgnoreCase(sort)){
//            sourceBuilder.sort("salesnum", SortOrder.DESC);
//        }else if("score".equalsIgnoreCase(sort)){
//            sourceBuilder.sort("scoreAvg", SortOrder.DESC);
//        }else if("speed".equalsIgnoreCase(sort)){
//            //速度
//            Map<String, Object> paramMapSpeed = new HashMap<>();
//            paramMapSpeed.put("lat", lat);
//            paramMapSpeed.put("lon", lon);
//            Script scriptSpeed = new Script(ScriptType.STORED, null, "runfast_bus_sortby_speed_asc", paramMapSpeed);
//            sourceBuilder.sort(SortBuilders.scriptSort(scriptSpeed, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC));
//        }else if("startPay".equalsIgnoreCase(sort)){
//            sourceBuilder.sort("startPay", SortOrder.ASC);
//        }else if("distributionfee".equalsIgnoreCase(sort)){
//            //配送费最低
//            Map<String, Object> paramMapDistributionfee = new HashMap<>();
//            paramMapDistributionfee.put("lat", lat);
//            paramMapDistributionfee.put("lon", lon);
//            paramMapDistributionfee.put("timeOf1790", timeOf1970);
//            Script scriptDistributionfee = new Script(ScriptType.STORED, null, "runfast_bus_sortby_distributionfee_asc", paramMapDistributionfee);
//            sourceBuilder.sort(SortBuilders.scriptSort(scriptDistributionfee, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC));
//        }else if("comprehensive".equalsIgnoreCase(sort)){
//            //综合排序
//            sourceBuilder.sort("priority", SortOrder.DESC).sort("goldBusiness", SortOrder.DESC);
//            sourceBuilder.sort("salesnum", SortOrder.DESC);
//            sourceBuilder.sort("scoreAvg", SortOrder.DESC);
//        }
//        sourceBuilder.sort(SortBuilders.geoDistanceSort("busPoint", lat, lon).unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC));
//        sourceBuilder.sort("id", SortOrder.ASC);
//        sourceBuilder.from((int)pageable.getOffset()).size(pageable.getPageSize());
//        searchRequest.indices(INDEX).types(TYPE).source(sourceBuilder);
//        System.out.println(searchRequest.source());
//        SearchResponse response = restHighLevelClient.search(searchRequest);
//        if(response.status() == RestStatus.OK) {
//            SearchHits hits = response.getHits();
//            if (hits != null) {
//                List<Object> objects = new ArrayList<>();
//                for (SearchHit hit : hits.getHits()) {
//                    Map sourceMap = hit.getSourceAsMap();
//                    if(sourceMap != null){
//                        Map<String, SearchHitField> hitFieldMap = hit.getFields();
//                        if(hitFieldMap != null){
//                            hitFieldMap.forEach((k, v) -> {
//                                sourceMap.put(k, v.getValue());
//                            });
//                        }
//                    }
//                    objects.add(sourceMap);
//                }
//                return WebResult.ok(new Page<>(hits.getTotalHits(), pageable.getPageNumber(), pageable.getPageSize(), objects));
//            }
//        }
//        return WebResult.fail("查询失败.");
//    }


}
